package com.flow.framework.registry.service.system.health.impl;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;

/**
 * nacos客户端健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/5
 */
@Slf4j
public class NacosRegistryClientHealthCheckServiceImpl implements IHealthCheckService {

    private final NacosAutoServiceRegistration nacosAutoServiceRegistration;

    /**
     * 创建nacos客户端健康检查服务
     *
     * @param nacosAutoServiceRegistration nacos自动注册管理器
     */
    public NacosRegistryClientHealthCheckServiceImpl(@Autowired(required = false) NacosAutoServiceRegistration nacosAutoServiceRegistration) {
        this.nacosAutoServiceRegistration = nacosAutoServiceRegistration;
    }

    /**
     * @inheritDoc
     */
    @Override
    public List<ServiceHealthVo> check() {
        try {
            if (null == nacosAutoServiceRegistration) {
                log.warn("nacos registry service is empty.");
                return Collections.singletonList(
                        SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CLIENT_CODE, null, null)
                );
            }
            boolean running = nacosAutoServiceRegistration.isRunning();
            if (!running) {
                return Collections.singletonList(
                        SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CLIENT_CODE, null, null)
                );
            }
            return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CLIENT_CODE));
        } catch (Exception e) {
            log.error("check nacos registry client status error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_REGISTRY_CLIENT_CODE, e.getMessage(), null)
            );
        }
    }
}
